import React from 'react';
import {Link} from 'react-router';
import config from '../../config';
import {formatDateLeave, formatDateBetween, getItem, isWeiXin} from '../../utils';
import {FETCH_ACT_LIST_DETAIL, FETCH_ACT_LIST_DETAIL_PERSON} from '../../constants/actTypes';
import {FOLLOW_ROOM, CANCEL_FOLLOW_ROOM} from '../../constants/actTypes';
import {Icon} from 'antd';

/**
 * 加载公共组件
 * */
import MainSection from '../../components/MainSection/MainSection';
import Avatar from '../../components/Avatar/Avatar';
import Price from '../../components/Price/Price';
import WeChatConfig from '../../components/WeChatConfig/WeChatConfig';

/**
 * 加载样式或图片文件
 * */
import './sass/activityListDetail.scss';

class ActivityListDetail extends React.Component {
    static timer = null;
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.handleFollow = this.handleFollow.bind(this);
        this.handleCancelFollow = this.handleCancelFollow.bind(this);
        this.renderControlBar = this.renderControlBar.bind(this);
        this.renderApplyVolBtn = this.renderApplyVolBtn.bind(this);
        this.setEventStatus = this.setEventStatus.bind(this);
        this.goApply = this.goApply.bind(this);
        this.state = {
            curAct: {
                room: {},
                sponsor: {},
                minAge: 0,
                maxAge: 0,
                price: 0,
                enrollCount: 0,
                amount: 0,
                volunteerCount: 0,
                volunteerAmount: 0,
                intro: '',
                volunteerIntro: '',
                personStatus: [],
                volunteerStatus: []
            },
            moreVisible: true,
            moreVisibleVol: true,
            actStatus: 1,
            leftSeconds: 0,

            eventStatus: 1000
        };
    }

    componentWillMount() {
        const {actions, params, act} = this.props;
        !!getItem('token') ? (
            actions.fetchActListDetailPerson(params.id).then(response => {
                if (response.type === FETCH_ACT_LIST_DETAIL_PERSON) {
                    setData(response);
                }
            })
        ) : (
            actions.fetchActListDetail(params.id).then(response => {
                if (response.type === FETCH_ACT_LIST_DETAIL) {
                    setData(response);
                }
            })
        );
        const setData = (response) => {
            if (response.data.code === 20000) {
                let curAct = response.data.data;
                if (curAct.status === 100) {
                    this.setState({
                        leftSeconds: (curAct.publishTime - Date.parse(new Date()) ) / 1000
                    });
                    this.setLeaveTime();
                }
                this.setState({
                    curAct: curAct
                }, () => {
                    const actIntroEl = document.querySelector('.act-intro');
                    const volIntroEl = document.querySelector('.vol-intro');
                    const maxHeight = 18 * 2;
                    if (actIntroEl.offsetHeight > maxHeight) {
                        this.setState({
                            moreVisible: false
                        })
                    } else {
                        this.setState({
                            moreVisible: true
                        })
                    }
                    if (volIntroEl.offsetHeight > maxHeight) {
                        this.setState({
                            moreVisibleVol: false
                        })
                    } else {
                        this.setState({
                            moreVisibleVol: true
                        })
                    }
                    this.setEventStatus();
                })
            } else {
                alert(response.data.message)
            }
        };
        // 设置微信转发信息
        this.setWxShare()

    }

    setEventStatus() {
        /**
         * 渲染底部状态 和 活动状态
         * 1001: 已报名
         * 1002: 名额已满
         * 1003: 已结束
         * 1004: 已取消
         */
        const curAct = this.state.curAct;
        if (curAct.status === 101 || curAct.status === 102) {  //报名中 进行中
            if (curAct.payStatus === 102) { // 已报名
                this.setState({eventStatus: 1001})
            }
            if (curAct.enrollCount >= curAct.amount) { // 名额已满
                this.setState({eventStatus: 1002})
            } else {

            }
        } else if (curAct.status === 100) {
        } else if (curAct.status === 103) {
            this.setState({eventStatus: 1003})
        } else if (curAct.status === 104) {
            this.setState({eventStatus: 1004})
        }
    }

    setLeaveTime() {
        this.timer = setInterval(() => {
            if (this.state.leftSeconds <= 1) {
                clearInterval(this.timer);
            } else {
                this.setState({
                    leftSeconds: this.state.leftSeconds - 1
                })
            }
        }, 1000)
    }

    setWxShare() {
        // const { curAct } = this.state;
        var _this = this;
        var wx = window.wx;
        wx.ready(function () {
            var data = {
                title: _this.state.curAct.name,
                link: location.href,
                imgUrl: 'https://dn-iclass.qbox.me/o_1bpo2il7a1jru1ul64rmnhg1gq87.png',
                desc: _this.state.curAct.intro,
                success: function () {
                    // console.log("分享成功")
                },
                cancel: function () {
                    // console.log("取消分享");
                }
            };
            // 朋友圈
            wx.onMenuShareTimeline(data);
            // 朋友
            wx.onMenuShareAppMessage(data);

        });
        wx.error(function (res) {
            console.log(res);
        });
    }

    componentWillUnmount() {
        this.setState({
            leftSeconds: 0
        });
        clearInterval(this.timer);

    }

    handleFollow() {
        const {actions} = this.props;
        let curAct = this.state.curAct;
        actions.followRoom({roomId: curAct.room.id}).then(res => {
            if (res.type === FOLLOW_ROOM) {
                if (res.data.code === 20000) {
                    // console.log('关注成功');
                    this.setState({
                        curAct: {
                            ...this.state.curAct,
                            room: {
                                ...this.state.curAct.room,
                                isFollow: 1
                            }
                        }
                    })
                } else if (res.data.code === 40001) {
                    alert(res.data.message);
                    window.location.href = config.SERVICE_URL + '/api/wechat/authorize?url=' + escape(config.JUMP_URL + '/#/login');
                    // this.context.router.push({
                    //     pathname: "/login"
                    // })
                } else {
                    alert(res.data.message)
                }
            }
        })
    }

    handleCancelFollow() {
        const {actions} = this.props;
        let curAct = this.state.curAct;
        actions.cancelFollowRoom({roomId: curAct.room.id}).then(res => {
            if (res.type === CANCEL_FOLLOW_ROOM) {
                if (res.data.code === 20000) {
                    // console.log('取消成功');
                    this.setState({
                        curAct: {
                            ...this.state.curAct,
                            room: {
                                ...this.state.curAct.room,
                                isFollow: 0
                            }
                        }
                    })
                }
            }
        })
    }

    renderApplyVolBtn() {
        const {params, actions, user, act} = this.props;
        const curAct = this.state.curAct;
        if ([103, 104].indexOf(curAct.status) > -1) {
            return (
                <span className="disabled-btn"><i className="icon-finish"/>报名截止</span>
            )
        } else {
            if (curAct.applyStatus === 102) {
                return (
                    <span className="disabled-btn"><i className="icon-finish"/>报名成功</span>
                )
            } else if (curAct.volunteerCount === curAct.volunteerAmount) {
                return (
                    <span className="disabled-btn"><i className="icon-finish"/>名额已满</span>
                )
            } else {
                return (
                    <Link to={'/activityList/' + params.id + '/applyVol'}
                          className="join-btn">+ 我要报名志愿者
                    </Link>
                )
            }
        }
    }


    goApply() {
        const curAct = this.state.curAct;

        curAct.payStatus === 101 ? (
            this.context.router.push({
                pathname: '/activityList/' + curAct.id + '/applyAct',
                state: {
                    comeFrom: 'order'
                }
            })
        ) : (
            this.context.router.push({
                pathname: '/activityList/' + curAct.id + '/applyAct'
            })
        );

    }

    renderControlBar() {
        const {params} = this.props;
        const curAct = this.state.curAct;


        if (curAct.status === 101 || curAct.status === 102) {  //报名中 进行中
            if (curAct.payStatus === 102) { // 已报名
            } else if (curAct.enrollCount >= curAct.amount) { // 名额已满
            } else {
                return (
                    <div className="control-bar">

                        <div className="join-able">
                            <p className="price-box color-6">总价:
                                {
                                    curAct.type === 101 && <Price num={curAct.price}/>
                                }
                                {
                                    curAct.type === 102 && <Price num={curAct.point} isScore={true}/>
                                }
                                /儿童</p>
                            <a className="join" onClick={this.goApply}>
                                {curAct.payStatus === 101 ? '去付款' : '确认报名'}
                            </a>
                        </div>
                    </div>
                )
            }
        } else if (curAct.status === 100) {
            return (
                <div className="control-bar">
                    <div className="join-wait">
                        <i className="icon-time"/>距开始报名:
                        {
                            formatDateLeave(this.state.leftSeconds)
                        }
                    </div>
                </div>
            )
        } else if (curAct.status === 103) {
        } else if (curAct.status === 104) {
        }
    }

    render() {
        const {params, actions, user, act} = this.props;
        const curAct = this.state.curAct;
        // console.log(curAct.volunteerIntro);
        return (
            <MainSection className="activity-list-detail" title="活动详情" notScroll={true}>
                <WeChatConfig actions={actions}/>
                <div className="banner-box">
                    {
                        curAct.image ?
                            <img className="banner" src={curAct.image + "?imageView2/1/w/375/h/200"} alt=""/> : null
                    }
                </div>

                <div className="act-info">
                    <div className="act-head act-row">
                        <h5>{curAct.name || ""}</h5>
                        <div className="label">
                            {
                                curAct.tags && curAct.tags.map((item, index) => {
                                    return (
                                        <span key={index}>{item.name}</span>
                                    )
                                })
                            }
                        </div>
                        <div className={"act-intro " + (this.state.moreVisible ? 'more' : '')}>
                            {
                                curAct.intro && curAct.intro.replace(/(\r\n|\n|\r)/g, "\n").split('\n').map((item, index) => {
                                    return (
                                        <p key={index}> {item} </p>
                                    )
                                })
                            }
                            {
                                this.state.moreVisible ? null :
                                    <span onClick={() => this.setState({moreVisible: true})}><em>更多</em></span>
                            }
                        </div>
                    </div>
                    <ul className={"act-body act-row mb30 status" + this.state.eventStatus}>
                        <li><span class="label">活动价格</span>
                            <em className="txt fs20">
                                {
                                    curAct.type === 101 && <Price num={curAct.price} size="sm"/>
                                }
                                {
                                    curAct.type === 102 && <Price num={curAct.point} isScore={true} size="sm"/>
                                }
                                /每位儿童
                                <span className="color-9">(成人免费)</span>
                            </em>
                        </li>
                        <li>
                            <span class="label">活动时间</span><
                            em className="txt">
                            {
                                (curAct.startTime && curAct.endTime) ? formatDateBetween(curAct.startTime, curAct.endTime) : null
                            }
                        </em>
                        </li>
                        <li><span class="label">活动地点</span><em
                            className="txt">{curAct.location}</em></li>
                        <li><span class="label">目标儿童</span><em
                            className="txt">{curAct.minAge + "-" + curAct.maxAge + "岁"}</em></li>
                    </ul>
                    {
                        !!curAct.room ? (
                            <Link className="act-master act-row mb30" to={"/sponsor?id=" + curAct.room.id}>
                                <Avatar src={curAct.room.avatar} isVip={true}/>
                                <div className="master-info">
                                    <h5><span>{curAct.room.name}</span> <i className="icon-master">主办方</i></h5>
                                    {
                                        // <p>{curAct.room.intro}</p>
                                    }
                                </div>
                                <Icon className="arrow" type="right"/>
                            </Link>
                        ) : (
                            <div className="act-master act-row">
                                <Link to="/sponsor">
                                    <Avatar src={curAct.sponsor.avatar}/>
                                    <div className="master-info">
                                        <h5>{curAct.sponsor.name} <i className="icon-master"/></h5>
                                        <p>培训累计时长:{curAct.sponsor.duration}小时 活动场次:{curAct.sponsor.amount}场</p>
                                    </div>
                                </Link>
                            </div>
                        )
                    }

                    <div className="act-apply act-row mb30">
                        <h5>已报名({curAct.enrollCount}/{curAct.amount})</h5>
                        {
                            curAct.personStatus.filter(item => item.payStatus === 102).length ? (
                                <Link className="vol-list" to={"/activityList/" + params.id + "/applyList"}>
                                    {
                                        curAct.personStatus.filter(item => item.payStatus === 102).map((item, index) => {
                                            return (
                                                <img key={index} src={item.avatar}/>
                                            )
                                        })
                                    }
                                    <Icon type="right"/>
                                </Link>
                            ) : (
                                <a className="vol-list">
                                    <span className="color-9">暂时没有人报名</span>
                                </a>
                            )
                        }
                    </div>
                    <div className="act-apply act-row">
                        {
                            this.renderApplyVolBtn()
                        }

                        <h5>志愿者({curAct.volunteerCount}/{curAct.volunteerAmount})</h5>
                        {
                            curAct.volunteerStatus && curAct.volunteerStatus.length ? (
                                <Link className="vol-list" to={"/activityList/" + params.id + "/applyVolList"}>
                                    {
                                        curAct.volunteerStatus.map((item, index) => {
                                            return (
                                                <img key={index} src={item.avatar}/>
                                            )
                                        })
                                    }
                                    <Icon type="right"/>
                                </Link>
                            ) : (
                                <a className="vol-list">
                                    <span className="color-9">暂时没有志愿者</span>
                                </a>
                            )
                        }
                        <div className="sub-title">志愿者任务:</div>
                        <div className='vol-intro  more'>
                            {
                                curAct.volunteerIntro && curAct.volunteerIntro.replace(/(\r\n|\n|\r)/g, "\n").split('\n').map((item, index) => {
                                    return (
                                        <div key={index}> {item} </div>
                                    )
                                })
                            }

                        </div>
                    </div>
                </div>
                {
                    this.renderControlBar()
                }


            </MainSection>
        );
    }
}

export default ActivityListDetail;